package com.h3c.nem.utils;

import com.h3c.nem.dto.sap.SapXmlResponseDTO;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author chenyifan
 * @date 2022/7/5 14:11
 */
public class XmlConvertUtil {
    /**
     * xml转换成JavaBean
     *
     * @param xml xml格式字符串
     * @param t 待转化的对象
     * @return 转化后的对象
     * @throws Exception JAXBException
     */
    @SuppressWarnings("unchecked")
    public static <T> T convertToJavaBean(String xml, Class<T> t) throws Exception {
        T obj = null;
        JAXBContext context = JAXBContext.newInstance(t);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        obj = (T) unmarshaller.unmarshal(new StringReader(xml));
        return obj;
    }

    /**
     * JavaBean转换成xml
     * @param obj
     * @param encoding
     * @return
     */
    public static String convertToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<soapenv:Envelope\n" +
                "    xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
                "    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
                "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                "    xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
                "    <soapenv:Body>\n" +
                "        <ns1:GETBDRESULTResponse\n" +
                "            xmlns:ns1=\"urn:DefaultNamespace\">\n" +
                "            <GETBDRESULTReturn>{\"success\": false,\"msg\":\"未找到录用编号或背调未通过\"}</GETBDRESULTReturn>\n" +
                "        </ns1:GETBDRESULTResponse>\n" +
                "    </soapenv:Body>\n" +
                "</soapenv:Envelope>\n";
        SapXmlResponseDTO responseDTO = convertToJavaBean(xml, SapXmlResponseDTO.class);
        System.out.println(responseDTO);
    }
}
